/*******************************************************************************
 * Copyright (c) 2009 Kevin Bierhoff and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Kevin Bierhoff - initial API and implementation
 *******************************************************************************/
package com.googlecode.twelfdevtools.model;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.texteditor.MarkerAnnotation;

class AnnotationBasedFileModel extends AbstractElfFileModel {
	
	private final IAnnotationModel model;

	/**
	 * Using this constructor will not allow binding variables
	 * defined in other files, but it's good enough for the outline
	 * @param model
	 */
	AnnotationBasedFileModel(IAnnotationModel model) {
		super(null, null);
		this.model = model;
	}
	
	/**
	 * This is quite the pain, we shouldn't have to pass in the
	 * annotation model <i>and</i> the file
	 * @param model
	 * @param parent
	 * @param resource
	 */
	AnnotationBasedFileModel(IAnnotationModel model,
			TwelfProjectImpl parent, IFile resource) {
		super(parent, resource);
		this.model = model;
	}
	
	@Override
	protected List<TwelfConstantImpl> getAllMarkers(String markerType, boolean includeSubtypes) {
		List<TwelfConstantImpl> result = new LinkedList<TwelfConstantImpl>();
		Iterator<?> it = model.getAnnotationIterator();
		while(it.hasNext()) {
			Annotation a = (Annotation) it.next();
			if(a instanceof MarkerAnnotation) {
				IMarker m = ((MarkerAnnotation) a).getMarker();
				try {
					if((includeSubtypes && m.isSubtypeOf(markerType)) || m.getType().equals(markerType)) {
						Position p = model.getPosition(a);
						// use getPosition to adjust for edits in the document
						result.add(createConstantModel(m, p));
					}
				} 
				catch (CoreException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
}
